import 'package:abc/controller/my_posts_controller.dart';
import 'package:abc/model/post_model.dart';
import 'package:abc/page/income_record_page.dart';
import 'package:abc/page/publish_post_page.dart';
import 'package:abc/page/withdraw_page.dart';
import 'package:abc/view/CustomAppBar.dart';
import 'package:abc/view/GradientButton.dart';
import 'package:abc/view/my_post_cell.dart';
import 'package:abc/view/pagination_list_view.dart';
import 'package:abc/view/post_cell.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

// 页面主色调
const Color darkBg = Color(0xFF1C1C2B);
const Color textColor = Colors.white;

class MyPostsPage extends GetView<MyPostsController> {
  const MyPostsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (!Get.isRegistered<MyPostsController>()) {
      Get.lazyPut(() => MyPostsController());
    }
    return Scaffold(
      backgroundColor: const Color(0xFF0E0F26), // 深色背景
      appBar: CustomAppBar(
        title: "我的帖子",
        onBack: () {
          Get.back();
        },
        rightWidget: InkWell(
          onTap: () {Get.to(() => const PublishPostPage());},
          child: Row(
            children: [
              Container(
                width: 22, // 宽高必须相等
                height: 22,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                child: Center(
                  child: Image.asset('assets/images/ic_add.png', height: 10),
                ),
              ),
              SizedBox(width: 2),
              Text(
                '发布',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 10.0,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ),
      ),
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            //  收益信息卡片
            SliverToBoxAdapter(child: _buildEarningsCard(darkBg, textColor)),

            //  TabBar 悬浮
            SliverPersistentHeader(
              delegate: _SliverAppBarDelegate(
                TabBar(
                  controller: controller.tabController,
                  padding: EdgeInsets.all(0),
                  labelPadding: EdgeInsets.zero,
                  dividerHeight: 0.5,
                  indicatorPadding: EdgeInsets.fromLTRB(
                    0.0,
                    kTextTabBarHeight - 3,
                    0.0,
                    0.0,
                  ),
                  indicator: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(2),
                    ),
                  ),

                  indicatorSize: TabBarIndicatorSize.label,
                  labelStyle: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                  unselectedLabelStyle: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                  labelColor: Colors.white,
                  unselectedLabelColor: Colors.white54,
                  tabs: controller.tabs.map((name) => Tab(text: name)).toList(),
                ),
              ),
              pinned: true, // TabBar 固定在顶部
            ),
          ];
        },
        // 4. 主体 TabBarView
        body: TabBarView(
          controller: controller.tabController,
          children: <Widget>[
            _buildPostListView(controller.publishedList), // 已发布
            _buildPostListView(controller.pendingList), // 待审核
            _buildPostListView(controller.failedList), // 审核失败
          ],
        ).paddingSymmetric(vertical: 10, horizontal: 16),
      ),
    );
  }

  // ---  收益卡片 ---
  Widget _buildEarningsCard(Color bgColor, Color textColor) {
    return Obx(() {
      final info = controller.earningsInfo.value;
      return Container(
        padding: EdgeInsets.only(top: 18),
        decoration: BoxDecoration(
          color: Color(0x33959595),
          borderRadius: BorderRadius.circular(10),
        ),

        child: Column(
          //crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            // 收益明细按钮
            InkWell(child: Container(
              alignment: Alignment.topRight,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),
                decoration: BoxDecoration(
                  color: Colors.white24,
                  borderRadius: BorderRadius.horizontal(
                    left: Radius.circular(10),
                  ),
                ),
                child: Text(
                  info.detailsButtonText,
                  style: TextStyle(
                    color: Colors.white60,
                    fontSize: 12,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),onTap: () {
              Get.to(IncomeRecordPage());
            },),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildEarningsItem('当前收益', info.currentEarnings),
                Container(width: 1, height: 30, color: Colors.white24),
                _buildEarningsItem('累计收益', info.totalEarnings),
              ],
            ),
            const SizedBox(height: 20),

            // 去提现按钮 (模拟渐变)
            SizedBox(
              width: 104,
              height: 35,
              child: ElevatedButton(
                onPressed: () => Get.to(() => const WithdrawPage()),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.zero,
                  elevation: 0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                ),
                child: Ink(
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [Color(0xFFA877F4), Color(0xFF5650D6)],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Container(
                    alignment: Alignment.center,
                    child: const Text(
                      '去提现',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(height: 14),
          ],
        ),
      ).paddingSymmetric(horizontal: 16);
    });
  }

  Widget _buildEarningsItem(String label, int value) {
    return Column(
      children: [
        Text(
          value.toString(),
          style: TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 6),
        Text(label, style: TextStyle(color: Color(0xFF999999), fontSize: 13)),
      ],
    );
  }

  Widget _buildPostListView(RxList<Post> postList) {
    return Obx(
      () => ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: postList.length,
        itemBuilder: (context, index) {
          return MyPostCell(
            post: postList[index],
            onDelete: () {
              // 删除回调处理
            },
          );
        },
      ),
    );
  }
}

// --- SliverPersistentHeaderDelegate 用于固定 TabBar ---
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar _tabBar;

  _SliverAppBarDelegate(this._tabBar);

  @override
  double get minExtent => _tabBar.preferredSize.height;
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(color: const Color(0xFF0E0F26), child: _tabBar);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) => false;
}
